package com.lintf.jwt.controller;

import com.lintf.jwt.entity.User;
import com.lintf.jwt.entity.UserPermissions;
import com.lintf.jwt.service.UserService;
import com.lintf.jwt.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/3/15-16:42
 * @ package_name:com.lintf.jwt.controller
 * @ project_name:SpringSecurity-JWT
 * @ desc:测试Api接口
 */
@Api(tags = "UserController", description = "后台用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public Result<User> register(@RequestBody User user) {
        User umsAdmin = userService.register(user);
        if (umsAdmin == null) {
            return Result.failed("注册失败，该用户已被注册！");
        }
        return Result.success(umsAdmin);
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping(value = "/login")
    public Result login(@RequestBody User user) {
        String token = userService.login(user.getUsername(), user.getPassword());
        if (token == null) {
            return Result.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        System.out.println("token:" + token);
        return Result.success(tokenMap);
    }
//      第一版
//    @ApiOperation("获取用户所有权限（包括+-权限）")
//    @GetMapping(value = "/permission/{userId}")
//    public Result<List<UserPermissions>> getPermissionList(@PathVariable Long userId) {
//        List<UserPermissions> permissionList = userService.getPermissionList(userId);
//        return Result.success(permissionList);
//    }

//    第二版
    @ApiOperation("获取用户所有权限（包括+-权限）")
    @GetMapping(value = "/permission/{username}")
    public Result<List<UserPermissions>> getPermissionList(@PathVariable String username) {
        List<UserPermissions> permissionList = userService.getPermissionList(username);
        return Result.success(permissionList);
    }

    @ApiOperation("根据条件获取所有的用户")
    @PostMapping(value = "/list")
    @PreAuthorize("hasAuthority('pms:brand:order')")
    public Result<List<User>> getuserList(@RequestBody User user) {
        List<User> list = userService.getlist(user);
        return Result.success(list);
    }
}


